<?php
namespace plugins\member\controller;
use cmf\controller\ApiPluginBaseController;
use plugins\member\validate\MemberValidate;
use plugins\member\model\MemberModel;
use think\Db;

class ApiIndexController extends ApiPluginBaseController
{
	//个人资料
	public function userData()
	{
		if($this->request->isPost()){
			$post = $this->request->post();
			$info = $this->getIdentity();
			$user = db('member')->field('uid',true)->where(['uid'=>$info->uid])->find();
			if($user){
				if($user['head_portrait'] != null){
					$user['head_portrait'] = zy_domain().$user['head_portrait'];
				}else{
					// $user['head_portrait'] = zy_domain()."/plugins/member/view/public/assets/user.png";
				}
				return api_json_echo(true,'查询完成',$user);
			}
			return api_json_echo(false,'查询失败，没有查询到对应用户');
		}
		return api_json_echo(false,'查询失败');
	}

    /**
     * 隐私设置-修改公开动态
     */
    public function openDynamic(){
        $param = $this->request->param();
        if(empty($param['userid'])){
            return api_json_echo(false, '未获取到userid！', null, 101);
        }
        $open_dynamic = 0;
        if(!empty($param['open_dynamic'])){
            $open_dynamic = $param['open_dynamic'];
        }
        $member = db('member')->where('uid',$param['userid'])->find();
        if(empty($member)){
            return api_json_echo(false, '未获取到用户信息！', null, 101);
        }
        $result = Db::name('member')->where('uid',$param['userid'])->update(['open_dynamic'=>$open_dynamic]);
        if($result){
            Db::name('community')->where('userid',$param['userid'])->update(['open_dynamic'=>$open_dynamic]);
            return api_json_echo(true,'修改完成');
        }
        return api_json_echo(false,'修改失败');
    }

    /**
     * 更新用户信息
     */
    public function updatePersonBg(){
        $param = $this->request->param();
        if(empty($param['userid'])){
            return api_json_echo(false, '未获取到userid！', null, 101);
        }
        $member = db('member')->where('uid',$param['userid'])->find();
        if(empty($member)){
            return api_json_echo(false, '未获取到用户信息！', null, 101);
        }
        if(!empty($param['bg_img'])){
            $update_data['bg_img'] = $param['bg_img'];
        }
        if(!empty($param['autograph'])){
            $update_data['autograph'] = $param['autograph'];
        }
        if(!empty($param['head_portrait'])){
            $update_data['head_portrait'] = $param['head_portrait'];
        }
        if(!empty($param['birthday'])){
            $update_data['birthday'] = $param['birthday'];
        }
        if(!empty($param['nick_name'])){
            $update_data['nick_name'] = $param['nick_name'];
        }
        if(!empty($param['sex'])){
            $update_data['sex'] = $param['sex'];
        }
        $update_data['edit_time'] = time();
        $result = Db::name('member')->where('uid',$param['userid'])->update($update_data);
        if($result){
            return api_json_echo(true,'修改完成');
        }
        return api_json_echo(false,'修改失败');
    }

    /**
     * 意见反馈
     */
    public function addFeedback(){
        $param = $this->request->param();
        if(empty($param['userid'])){
            return api_json_echo(false, '未获取到userid！', null, 101);
        }

        if(!empty($param['title'])){
            $update_data['title'] = $param['title'];
        }
        if(!empty($param['content'])){
            $update_data['content'] = $param['content'];
        }
        $update_data['userid'] = $param['userid'];
        $update_data['addtime'] = time();
        $result = Db::name('feedback')->insert($update_data);
        if($result){
            return api_json_echo(true,'提交成功');
        }
        return api_json_echo(false,'提交失败');
    }


    //个人资料
    public function getUserInfo()
    {
        $post = $this->request->post();
        if($post['uid'] == 10001001){
            $user = db('user')->where(['employee_id'=>$post['uid']])->find();
            if(!empty($user)){
                $user['nick_name'] = '客服';
                $user['head_portrait_full'] = ZY_APP_PATH.'/plugins/member/view/public/kf.png';
            }
        }else{
            $user = db('member')->where(['uid'=>$post['uid']])->find();
            if(!empty($user)){
                $user['head_portrait_full'] = ZY_APP_PATH.$user['head_portrait'];
            }
        }
        if($user){
            return api_json_echo(true,'查询完成',$user);
        }
        return api_json_echo(false,'查询失败，没有查询到对应用户');
    }
	//修改登陆密码
	public function changePassword()
	{
		if($this->request->isPost()){
			$post = $this->request->post();
			$info = $this->getIdentity();
			if($post['data']['new_password'] != $post['data']['re_password']){
				return api_json_echo(false,'两次密码不相同，请重新输入');
			}
			$member = ( new MemberModel )->get(['uid'=>$info->uid,'password'=>cmf_password($post['data']['old_password'])]);
			if($member == null){
				return api_json_echo(false,'旧密码错误，请重试');
			}
			//检测通过后
			$member->password = '';
			$member->save();
			$member->password = cmf_password($post['data']['new_password']);
			$result = $member->save();
			if($result){
				return api_json_echo(true,'修改完成');
			}
			return api_json_echo(false,'修改失败');
		}
		return api_json_echo(false,'查询失败，错误的地址');
	}

    //更新cid
    public function updateCid()
    {
        if($this->request->isPost()){
            $post = $this->request->post();

            $result = Db::name('member')->where('uid',$post['uid'])->update(['cid'=>$post['cid']]);
            if($result){
                return api_json_echo(true,'修改完成');
            }
            return api_json_echo(false,'修改失败');
        }
        return api_json_echo(false,'查询失败，错误的地址');
    }

    //获取cid
    public function getCid()
    {
        if($this->request->isPost()){
            $post = $this->request->post();

            $result = Db::name('member')->where('uid',$post['uid'])->find();
            if($result){
                return api_json_echo(true,'查询成功',$result);
            }
            return api_json_echo(false,'查询失败');
        }
        return api_json_echo(false,'查询失败，错误的地址');
    }

    //修改登陆密码
    public function editPassword()
    {
        if($this->request->isPost()){
            $data = $this->request->post();

            //验证参数
            $check['phone'] = ['name'=>'手机号码','type'=>'require|regex:/^1[34578]\d{9}$/','message'=>['regex'=>'请输入正确的手机号码']];
            $check['code'] = ['name'=>'验证码'];
            checkParam($check,$data);

            //手机验证码检测
            $check_code = cmf_check_verification_code($data['phone'], $data['code'],true);
            if($check_code != ''){
                return api_json_echo( false , $check_code);
            }

            if($data['new_password'] != $data['re_password']){
                return api_json_echo(false,'两次密码不相同，请重新输入');
            }

            $member = ( new MemberModel )->get(['phone'=>$data['phone']]);
            if($member == null){
                return api_json_echo(false,'该用户未注册');
            }
            //检测通过后
            $member->password = '';
            $member->save();
            $member->password = cmf_password($data['new_password']);
            $result = $member->save();
            if($result){
                return api_json_echo(true,'修改完成');
            }
            return api_json_echo(false,'修改失败');
        }
        return api_json_echo(false,'查询失败，错误的地址');
    }


	//修改所在城市
	public function changeCity()
	{
		if($this->request->isGet()){
			$get = $this->request->get();
			$info = $this->getIdentity();
			$member = ( new MemberModel )->get(['uid'=>$info->uid]);
			if($member){
				$city = $member->city;

				return api_json_echo(true,'查询完成',$city);
			}
			return api_json_echo(false,'未查询到用户');
		}
		if($this->request->isPost()){
			$post = $this->request->post();
			$info = $this->getIdentity();
			$member = ( new MemberModel )->get(['uid'=>$info->uid]);
			if($member){
				$member->city = $post['city'];
				$result = $member->save();
				if($result){
					return api_json_echo(true,'修改完成');
				}
				return api_json_echo(false,'修改失败');
			}
			return api_json_echo(false,'未查询到用户');
		}
	}
	//修改出生日期
	public function changeBirthday()
	{
		if($this->request->isGet()){
			$get = $this->request->get();
			$info = $this->getIdentity();
			$member = ( new MemberModel )->get(['uid'=>$info->uid]);
			if($member){
				$birthday = $member->birthday;
				return api_json_echo(true,'查询完成',$birthday);
			}
			return api_json_echo(false,'未查询到用户');
		}
		if($this->request->isPost()){
			$post = $this->request->post();
			$info = $this->getIdentity();
			$member = ( new MemberModel )->get(['uid'=>$info->uid]);
			if($member){
				$member->birthday = $post['birthday'];
				$result = $member->save();
				if($result){
					return api_json_echo(true,'修改完成');
				}
				return api_json_echo(false,'修改失败');
			}
			return api_json_echo(false,'未查询到用户');
		}
	}
	//修改个人简介
	public function changeIndividual()
	{
		if($this->request->isGet()){
			$get = $this->request->get();
			$info = $this->getIdentity();
			$member = ( new MemberModel )->get(['uid'=>$info->uid]);
			if($member){
				$individual = $member->individual;
				return api_json_echo(true,'查询完成',$individual);
			}
			return api_json_echo(false,'未查询到用户');
		}
		if($this->request->isPost()){
			$post = $this->request->post();
			$info = $this->getIdentity();
			$member = ( new MemberModel )->get(['uid'=>$info->uid]);
			if($member){
				$member->individual = $post['individual'];
				$result = $member->save();
				if($result){
					return api_json_echo(true,'修改完成');
				}
				return api_json_echo(false,'修改失败');
			}
			return api_json_echo(false,'未查询到用户');
		}
	}
	//修改头像
	public function changeHeadImg()
	{
		if($this->request->isGet()){
			$get = $this->request->get();
			$info = $this->getIdentity();
			$member = ( new MemberModel )->get(['uid'=>$info->uid]);
			if($member){
				if($member->head_portrait != null){
					$head_portrait = zy_domain().$member->head_portrait;
				}else{
					$head_portrait = zy_domain()."/plugins/member/view/public/assets/user.png";
				}

				return api_json_echo(true,'查询完成',$head_portrait);
			}
			return api_json_echo(false,'未查询到用户');
		}
		if($this->request->isPost()){
			$post = $this->request->post();
			$info = $this->getIdentity();
			$member = ( new MemberModel )->get(['uid'=>$info->uid]);
			if($member){
				$image = $this->base64_image_content($post['head_portrait']);
				$member->head_portrait = $image;
				$result = $member->save();
				if($result){
					return api_json_echo(true,'修改完成',zy_domain().$member->head_portrait);
				}
				return api_json_echo(false,'修改失败');
			}
			return api_json_echo(false,'未查询到用户');
		}
	}
	//修改性别
	public function changeSex()
	{
		if($this->request->isGet()){
			$get = $this->request->get();
			$info = $this->getIdentity();
			$member = ( new MemberModel )->get(['uid'=>$info->uid]);
			if($member){
				$sex = $member->sex;
				return api_json_echo(true,'查询完成',$sex);
			}
			return api_json_echo(false,'未查询到用户');
		}
		if($this->request->isPost()){
			$post = $this->request->post();
			$info = $this->getIdentity();
			$member = ( new MemberModel )->get(['uid'=>$info->uid]);
			if($member){
				$member->sex = $post['sex'];
				$result = $member->save();
				if($result){
					return api_json_echo(true,'修改完成');
				}
				return api_json_echo(false,'修改失败');
			}
			return api_json_echo(false,'未查询到用户');
		}
	}
	//修改昵称
	public function changeNickName()
	{
		if($this->request->isPost()){
			$post = $this->request->post();
			$info = $this->getIdentity();
			$member = ( new MemberModel )->get(['uid'=>$info->uid]);
			$member->nick_name = '';
			$member->save();
			$member->nick_name = $post['nick_name'];
			$result = $member->save();
			if($result){
				return api_json_echo(true,'修改完成');
			}
			return api_json_echo(false,'修改失败');
		}
		return api_json_echo(false,'查询失败');
	}
	//验证手机
	public function checkPassword()
	{
	}
    /**
     * [base64_image_content base64编码字符串 保存并生成图片链接]
     * @param  [type] $image [base64编码字符串]
     * @return [type]        [description]
     */
    private function base64_image_content($image){
        if($image == base64_encode(base64_decode($image))){
            return $image;
        }
        $sui=mt_rand(10000,99999);
        $imageName = date('Ymd').'/'.$sui.date('His').".png"; //设置生成的图片名字
        if (strstr($image,",")){
            $image = explode(',',$image);
            $image = $image[1];
        }
        //获取网站路径
        $http_type = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) ? 'https://' : 'http://';
        $wzurl = $http_type.$_SERVER['HTTP_HOST'].$_SERVER['SCRIPT_NAME'];
        $wzurl= substr($wzurl,0,strrpos($wzurl,'/'));
        $this->uploadpath = ROOT_PATH.'public/plugins/member/view/public/assets/images/default';
        $path =  $this->uploadpath;
        // $path = "./upload/pingjia"; // 设置图片保存路径
        if (!is_dir($path.'/'.date('Ymd'))){ //判断目录是否存在 不存在就创建 并赋予777权限
            mkdir($path.'/'.date('Ymd'),0777,true);
        }
        $imageSrc= $path."/". $imageName; //图片名字
        $r = file_put_contents($imageSrc, base64_decode($image));//返回的是字节数
        if (!$r) {
            return zy_json_echo(error,'图片生成失败',null,-1);
        }else{
            // $pic = explode('.',$imageSrc,2)['1'];
            return "/plugins/member/view/public/assets/images/default/".$imageName;
        }
    }
	//登录后发短信
	public function sendCode()
	{
		$info = $this->getIdentity();
		$member = ( new MemberModel )->get(['uid'=>$info->uid]);
		//验证码生成
		$code = cmf_get_verification_code($member->phone, 6);
		if($code == false){
			return api_json_echo( false , '发送失败，今日发送次数已达到15次上限' , $code );
		}
		//验证码发送
		$data = [
            'mb_name' => 'verify_code', //模板标识,项目中可自定义,定义以后到短信配置做相应的模板配置, 但是在写标准基础模块和插件时必须按照规范书写,方便复用
            'mobile' => $member->phone,//手机号
            'content' => [  //发送内容,用于存放模板变量, 默认可以设置 [] 空数组,
                'code' => $code
            ]
        ];
        $return = cmf_sms_send( $data );
        if($return['status'] == true){
	 		//更新验证码发送日志
			$result = cmf_verification_code_log($member->phone, $code, (time()+300));
			if($result){
				return api_json_echo( true , '发送成功');
			}else{
				return api_json_echo( false , '发送失败');
			}
        }else{
        	return api_json_echo( false , '发送失败');
        }
	}
	//登陆后检查短信验证码
	public function checkCode()
	{
		$post = $this->request->post();
		$info = $this->getIdentity();
		$member = ( new MemberModel )->get(['uid'=>$info->uid]);
		//手机验证码检测
		$check_code = cmf_check_verification_code($member->phone, $post['code'],true);
		if($check_code != ''){
			return api_json_echo( false , $check_code);
		}
		return api_json_echo( true , '验证成功');
	}
	//更换手机号
	public function changePhone()
	{
		$post = $this->request->post();
		$info = $this->getIdentity();

		$member = ( new MemberModel)->get(['uid'=>$info->uid]);
		if(!preg_match("/^1[34578]\d{9}$/", $post['phone'])){
			return api_json_echo( false , '请输入正确的手机号' );
		}
		//验证手机验证码
		$check_code = cmf_check_verification_code($post['phone'], $post['code'],true);
		if($check_code != ''){
			$result = $member->save(['phone'=>$post['phone']]);
			if($result){
				return api_json_echo(true,'更换手机号成功!');
			}
			return api_json_echo(false,'更换失败请重试');
		}
		return api_json_echo(false,'验证码输入错误请重试');
	}
}
